<template>
  <div>
    <div>
      <FormPanel ref="formPanel" :list="formList" :cols="2" :formType="type" labelWidth="110" :isSubmitBtn="false" @formChange="formChangeHandle" />
    </div>
    <BreakSpace label="来源渠道" />
    <FilterTable
      ref="table"
      lazy
      :tree-props="{ children: 'source_id', hasChildren: 'up_clue_id' }"
      :visible.sync="visible"
      :columns="columns"
      :params="fetchParams"
      :fetchapi="fetchApi"
      :onSelectTable="selectTable"
      :onSyncTableData="syncTableData"
      :datakey="'records'"
      :onColumnsChange="columns => (this.columns = columns)"
      :dataSource="tablelist"
    >
      <template slot="controls" slot-scope="props">
        <el-button v-if="isDownloadTemplate" size="small" type="primary" icon="el-icon-plus" @click="selectChannelType()">新增来源渠道</el-button>
        <el-button v-if="isDownloadTemplate" size="small" type="primary" icon="el-icon-plus" @click="deleteChannelType()">删除来源渠道</el-button>
      </template>
    </FilterTable>

    <!-- 来源渠道弹窗 -->
    <BaseDialog title="来源渠道查询" :visible.sync="visibleSource" width="1000px" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <sourceMadal ref="addDialogRef" selectType="single" :type="channelType" @close="closeSource" />
    </BaseDialog>

    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <el-button @click="closeDialog">取 消</el-button>
      <AjaxButton :click="saveDialog" type="primary">保存</AjaxButton>
    </div>
  </div>
</template>

<script>
import { queryCleanTaskSource, updateCleanTask, insertCleanTask } from '@/api/potenCus/basedata/dealerBlacklist';
import { dictionary } from '@/utils/dictMixin';
import dealerBlacklistModel from './dealerBlacklistModel';
import sourceMadal from '@/pages/cms-common/source/indexotherClean';
import { notifyAction } from '../../../../utils';
export default {
  name: 'dealerBlacklistModels',
  mixins: [dictionary],
  components: {
    dealerBlacklistModel,
    sourceMadal
  },
  props: {
    type: {
      type: String,
      default: 'add'
    },
    rowData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      // topFilterList: this.createTopFilters(),
      fetchParams: { xhrAbort: true },
      visibleSource: false,
      visible: false,
      dialogTitle: '',
      isDownloadTemplate: true,
      fetchApi: queryCleanTaskSource,
      clueSource: '',
      formList: this.createFromColumns(),
      columns: this.createTableColumns(),
      clueSource: [],
      clueSourceName: [],
      channelType: '',
      tablelist: [],
      handleType: '',
      formData: {},
      tableData: [],
      selectList: [],
      conf: { add: '新增', edit: '编辑', show: '显示' },
      selectedRow: null
    };
  },
  methods: {
    syncTableData(val) {
      debugger
      this.tableData = val;
      let name = '';
      val.forEach(x => {
        name = name + "【" + x.clueName + "】；";
      });
      if (name.length > 1) {
        name = name.substring(0, name.length - 1);
      }
      this.formList.find(x => x.fieldName == 'sourceChannel').initialValue = name;
    },
    init() {
      this.fetchParams = Object.assign({ xhrAbort: false }, { cleanTaskId: this.rowData.cleanTaskId });
      if (this.type === 'edit') {
        // 更新接口需要的记录 ID
        this.recordId = this.rowData.failModelId;
        this.formList.forEach(x => {
          if (x.fieldName == 'isActivity') {
            this.rowData[x.fieldName] = Number(this.rowData[x.fieldName]);
          }
          x.initialValue = this.rowData[x.fieldName];
        });
      } else {
        this.fetchParams = Object.assign({ xhrAbort: false }, { cleanTaskId: null });
      }

      if (this.formList.find(x => x.fieldName == 'isClean').initialValue == 10041001) {
        this.isDownloadTemplate = false;
      }
    },

    selectTable(row, index) {
      this.selectList = row;
    },
    createFromColumns() {
      return [
        {
          type: 'INPUT',
          label: '任务代码',
          readonly: true,
          disabled: true,
          fieldName: 'taskNum'
        },
        // {
        //   type: 'INPUT',
        //   label: '任务代码',
        //   readonly: true,
        //   disabled: true,
        //   fieldName: 'cleanTaskId'
        //   // hidden: true
        // },
        {
          type: 'SELECT',
          label: '是否启用',
          placeholder: '请输入...',
          itemList: this.createDictList('1004'),
          fieldName: 'isActivity',
          rules: [{ required: true, message: '请选择是否启用', trigger: 'blur' }]
        },
        {
          type: 'TEXT_AREA',
          label: '任务描述',
          rows: 3,
          placeholder: '请输入...',
          fieldName: 'taskName',
          rules: [{ required: true, message: '请输入任务描述', trigger: 'blur' }]
        },
        {
          type: 'DATE',
          label: '任务开始日期',
          valueFormat: 'yyyy-MM-dd',
          placeholder: '请选择...',
          fieldName: 'taskStDate',
          rules: [{ required: true, message: '请选择任务开始日期', trigger: 'blur' }]
        },
        {
          type: 'DATE',
          label: '任务结束日期',
          valueFormat: 'yyyy-MM-dd',
          placeholder: '请选择...',
          fieldName: 'taskEnDate',
          rules: [{ required: true, message: '请选择任务结束日期', trigger: 'blur' }]
        },
        {
          type: 'SELECT',
          label: '是否一键清洗',
          placeholder: '',
          itemList: this.createDictList('1004'),
          span: 2,
          initialValue: 10041002,
          fieldName: 'isClean',
          rules: [{ required: true, message: '请选择是否一键清洗', trigger: 'blur' }],
          change: val => {
            if (val == 10041002) {
              this.formList.find(x => x.fieldName == 'cleanType').disabled = true;
              this.formList.find(x => x.fieldName == 'cleanType').initialValue = '';
              this.isDownloadTemplate = true;
            } else {
              this.formList.find(x => x.fieldName == 'cleanType').disabled = false;
              this.formList.find(x => x.fieldName == 'cleanType').initialValue = '';
              this.isDownloadTemplate = false;
            }
          }
        },
        {
          type: 'SELECT',
          label: '一键清洗渠道类型',
          placeholder: '',
          itemList: this.createDictList('2589'),
          fieldName: 'cleanType'
        },
        {
          type: 'TEXT_AREA',
          label: '来源渠道',
          selfCols: 2,
          rows: 7,
          placeholder: '',
          readonly: true,
          disabled: true,
          fieldName: 'sourceChannel'
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },

        {
          title: '描述',
          dataIndex: 'clueName',
          sorter: true,
          width: 500,
          filter: true,
          filterType: 'input'
        },
        {
          title: '数据类型',
          dataIndex: 'dataType',
          itemList: this.createDictList('7026'),
          sorter: true,
          filter: true,
          render: props => {
            return <span>{this.createDictText(props.row.dataType, '7026')}</span>;
          },
          filterType: 'input'
        },
        {
          title: '有效性',
          dataIndex: 'isEnable',
          sorter: true,
          filter: true,
          render: props => {
            return <span>{this.createDictText(Number(props.row.isEnable), '1001')}</span>;
          },
          itemList: this.createDictList('1001'),
          filterType: 'input'
        }
      ];
    },
    selectChannelType() {
      let cleanType = this.formList.find(x => x.fieldName == 'cleanType').initialValue;
      this.channelType = cleanType + '';
      this.visibleSource = true;
    },
    deleteChannelType() {
      this.$confirm('是否确定删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$refs.table.EXECUTE_DELETE(this.selectList);
          // this.delete(No);
        })
        .catch(() => { });
    },

    formChangeHandle(val) {
      this.saveData = val;
    },
    addHandle() {
      this.handleType = 'add';
      this.showHandler();
    },
    editHandle(row) {
      this.handleType = 'edit';
      this.formData = row;
      this.showHandler();
    },
    showHandler() {
      this.dialogTitle = `设置${this.conf[this.handleType]}`;
      this.visible = true;
    },
    changeHandle(val) {
      this.fetchParams = Object.assign({ xhrAbort: false }, val);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    // 来源渠道关闭窗口 -返回数据

    closeSource(data) {
      console.log('-=-=-=-=-=-=-=', data);
      if (data && data.length > 0) {
        //循环返回数 据
        let flag = false;
        let clueSourceArray = [];
        let clueSourceNameArray = [];
        data.forEach(x => {
          clueSourceArray.push(x.id);
          clueSourceNameArray.push(x.clueName);
          this.tableData.forEach(y => {
            if (x.id == y.id || x.id == y.sourceId) {
              flag = true;
              return;
            }
          });
        });
        if (flag) {
          this.$message.error('不能插入相同渠道!');
          return;
        }
        this.$refs.table.$refs.pageTable.EXECUTE_INSERT(data);
      }

      //关闭弹窗
      this.visibleSource = data.visible;
    },
    closeHandler(val, type) {
      this.visible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    selectChangeHandle(rows) {
      if (!rows.length) return;
      this.selectedRow = rows;
    },

    closeDialog(param) {
      //取消按钮
      this.$emit('close', false, param);
    },
    async saveDialog() {
      let forms = this.$refs.formPanel.SUBMIT_FORM();
      forms.channelList = this.tableData;
      forms.deleteChannelList = this.$refs.table.GET_DELETE_ROWS();
      if (forms.channelList && forms.channelList.length > 0) {
        forms.channelList.forEach(x => {
          x.sourceId = x.sourceId ? x.sourceId : x.id;
        });
      }
      if (this.type == 'edit') {
        forms.cleanTaskId = this.rowData.cleanTaskId;
      } else {
        forms.cleanTaskId = null;
      }
      forms.taskEnDate = forms.taskEnDate.length <= 11 ? forms.taskEnDate + '23:59:59' : forms.taskEnDate;
      forms.taskStDate = forms.taskStDate.length <= 11 ? forms.taskStDate + '00:00:00' : forms.taskStDate;
      const res = await insertCleanTask(forms);
      if (res.resultCode === 200) {
        this.$message.success('保存成功!');
        this.closeDialog('refresh');
      }
    }
  },
  mounted() {
    this.init();
  },
  created() {
    if (this.formList.find(x => x.fieldName == 'isClean').initialValue === 10041001) {
      this.formList.find(x => x.fieldName == 'cleanType').disabled = false;
    } else {
      this.formList.find(x => x.fieldName == 'cleanType').disabled = true;
    }
  }
};
</script>

<style lang="less" scoped></style>
